<template>
  <div class="product-template-edit-container" v-loading.fullscreen.lock="loadingPage">

    <!-- start 新建编辑表单 -->
    <form @submit.prevent="submit" class="base-form bbx-normal-page-box" v-if="init" novalidate>

      <!-- start 页面顶部按钮 -->
      <div class="flex-x page-title">
        <div class="flex-1">
          <div class="title">
          </div>
          
        </div>
        <FormCellChange
          class="mar-r-8"
          :count="formCellCount"
          @update="
            e => {
              formCellCount = e;
            }
          "
        ></FormCellChange>
        <el-button type="primary" native-type="submit" :disabled="pending">{{ $t('common.base.save') }}</el-button>
        <!-- end 页面顶部按钮 -->
      </div>
      <div :class="['flex-1 scroll-y', formCellCount > 1 ? 'bbx-normal-form-builder-cell' : '']">
        <!-- start form builder -->
        <form-builder ref="productTemplateEditForm" class="bbx-cell-form-builder" :fields="fields" mode="productTemplate" :value="form" @update="update" :form-cell-count="formCellCount">
          <!-- start 产品类型 old -->
          <template slot="type" slot-scope="{field}">
            <form-item :label="field.displayName" class="bbx-form-cell-item" validation>
              <div class="input-and-btn">
                <form-select
                  :field="field" 
                  :source="field.setting.dataSource.map(d => {
                    return {
                      text: d,
                      value: d
                    }
                  }) || []"
                  v-model="form.type"
                  :clearable="false"
                  :placeholder="genPlaceholder(field)"/>
              </div>
            </form-item>
          </template>
        <!-- end 产品类型 old -->
        <!-- start 产品类型 new -->
        <template slot="catalogId" slot-scope="{ field }">
          <form-item :label="field.displayName" class="bbx-form-cell-item" :validation='validation'>
            <form-cascader :field='field' :tree='catalogTree' version='new' :value='catalog' :remote-search="true" @input='catalogInput' @beforeFilter="beforeFilter"></form-cascader>
          </form-item>
        </template>
        <!-- end 产品类型 new -->
        
        </form-builder>
      <!-- end form builder -->
    </div>

    </form>
    <!-- end 新建编辑表单 -->

  </div>
</template>

<script>
/* api */
import {
  productTemplateCreate,
  productTemplateUpdate,
  getProductTemplate,
  getProductFields
} from '@src/api/ProductApi'
/* enum */
import TenantDataLimitSourceEnum from '@model/enum/TenantDataLimitSourceEnum'
import TenantDataLimitTypeEnum from '@model/enum/TenantDataLimitTypeEnum'
/* mixin */
import VersionMixin from '@src/mixins/versionMixin/index.ts'
import ThemeMixin from '@src/mixins/themeMixin/index.ts'
/* util */
import * as FormUtil from '@src/component/form/util'
import platform from '@src/platform'
import { cloneData, queryCatalogTree } from "@src/api/ProductV2Api";
import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { debounce } from 'lodash' 
import { useFormTimezone, formatAddress } from 'pub-bbx-utils'
const { disposeFormSubmitTime } = useFormTimezone()
import FormCellChange from '@src/component/compomentV2/FormCellChange/index.vue';

export default {
  name: 'product-template-edit',
  mixins: [VersionMixin, ThemeMixin],
  props: {
    initData: {
      type: Object,
      default: () => ({})
    }
  },
  components:{
    FormCellChange
  },
  data() {
    return {
      hasRepeatRepair:false,
      // 权限
      auth: {},
      // 字段列表
      fieldsLocal: [],
      // 表单数据
      form: {
        name: '',
        serialNumber: '',
        type: ''
      },
      // 初始化
      init: false,
      // 加载页面
      loadingPage: false,
      // 等待状态
      pending: false,
      fieldsInfo: [],

      catalogTree:[],
      catalog:[],
      formCellCount:1
    }
  },
  computed: {
    action() {
      return this.initData.action
    },
    editId() {
      return this.initData.id
    },
    fields() {
      let originFields = (this.fieldsInfo.filter(f => {
        return (
          f.fieldName !== 'customer'
          && f.fieldName !== 'tags'
          && f.fieldName !== 'qualityInfo'
        )
      })
      );
      let localFields = this.fieldsLocal;
      let fields = [...localFields, ...originFields];

      let sortedFields = fields.sort((a, b) => a.orderId - b.orderId)
        .map(f => {
          if (f.formType === 'address' && f.isSystem) {
            f.isNull = this.initData.isAddressAllowNull ? 1 : 0;
          }
          return f;
        });
      
      return FormUtil.migration(sortedFields)
    }
  },
  async mounted() {
    const { status, data, message } = await getProductFields({isFromSetting:true});
    if( status == 0 ){
      this.fieldsInfo = data;
      this.fieldsInfo.forEach(field => {
        if (field.fieldName == 'isRepeatRepair') {
          this.hasRepeatRepair = true
        }
      })
      // 过滤不能编辑的自定义字段 不展示(是否重复报修)
      // 暂时屏蔽掉产品地址新系统字段后续再做兼容
      this.fieldsInfo = this.fieldsInfo.filter(field => field.setting?.isEdit != 0 && field.fieldName !== 'productCompleteAddress' && field.fieldName !== 'serviceProviders')
    }
    // 初始化默认值
    let form = {}
    // 编辑
    if(this.action == 'edit' && this.initData.id) {
      try {
        this.toggleLoading(false)

        let result = await getProductTemplate(this.initData.id);

        form = result;

        if(form.attribute) {
          form = {
            ...form,
            ...form.attribute
          }
        }
      } catch(err) {
        console.error(`productTemplate edit mounted err ${err}`)
      } finally {
        this.toggleLoading(false)
      }
      
    } else {
      // 检查版本数量限制
      this.checkNumExceedLimitBeforeHandler
      && this.checkNumExceedLimitBeforeHandler(
        TenantDataLimitSourceEnum.Product,
        TenantDataLimitTypeEnum.ProductTemplate
      )
    }

    this.form = FormUtil.initialize(this.fields, form)
    this.init = true

    this.getTreeList();
  },
  methods: {
    // 产品类型远程搜索
    beforeFilter: debounce(async function(value){
      if(!value) return this.getTreeList();
      try {
        const { code, message, result } = await queryCatalogTree({ keyWord: value });
        if (code === 0) {
          this.deleteEmpty(result);
          this.catalogTree = result;
          this.initCatalog();
        } else {
          this.$platform.notification({
            type: 'error',
            title: '请求错误',
            message: message
          })
        }
      } catch (err) {
        console.error(err);
      }
    }, 500),

    catalogInput(value){
      const length=value.length;
      this.catalog=value;
      const field=this.fields.find(item=>item.fieldName === 'catalogId');
      this.update({field,newValue:length?value[length-1]:''})
    },
    validation(){
      return new Promise((resolve, reject) => {
        if(!this.catalog.length) {
          return resolve(this.$t('product.form.validationTips.catalogId'));
        } 
        resolve(null);
      })
    },
    initCatalog(){
      const keys=Object.keys(this.form);
      const catalogKey=keys.find(key=>key==='catalogId');
      if(catalogKey){
        const id=this.form[catalogKey];
        let treeArr=[];
        this.flat(this.catalogTree,treeArr);
        if(id) this.getCatalogParents(id,treeArr,this.catalog);
      }
    },
    // 拉平产品类型树
    flat(tasks,arr){
      tasks.forEach(item=>{
        arr.push(item);
        if(item.tasks && item.tasks.length){
          this.flat(item.tasks,arr);
        }
      });
    },
    // 获取产品类型id及其父级
    getCatalogParents(id,treeArr,catalogArr){
      catalogArr.unshift(id);
      const item=treeArr.find(t=>t.id===id);
      if(item && item.parentId){
        this.getCatalogParents(item.parentId,treeArr,catalogArr);
      }
    },
    async getTreeList(){
      try{
        const {code,message,result}=await cloneData();
        if(code===0){
          this.deleteEmpty(result);
          this.catalogTree=result;
          this.initCatalog();
        }else{
          this.$platform.notification({
            type: 'error',
            title: this.$t('common.base.requestError'),
            message: message
          })
        }
      }catch(err){
        console.error(err);
      }
    },
    // 删除空子集
    deleteEmpty(list){
      list.forEach(item=>{
        if(!item.tasks.length){
          delete item.tasks;
        }else{
          this.deleteEmpty(item.tasks);
        }
      });
    },
    createProductTemplate(params) {
      const CreateProductPromise = productTemplateCreate(params)

      this.checkNumExceedLimitAfterHandler(CreateProductPromise)
        .then(res => {
          const isSucc = (res.succ === true)

          platform.notification({
            type: isSucc ? 'success' : 'error',
            title: isSucc ? this.$t('product.productTemplate.tips.tip6') : this.$t('product.productTemplate.tips.tip7'),
            message: !isSucc && res.message
          })
          
          if(isSucc) {
            this.closeAndOpenTab(res.data);
          }

        })
        .catch(err => {
          console.error('err', err)
        })
        .finally(() => {
          this.toggleLoading(false)
        })
    },
    editProductTemplate(params) {
      productTemplateUpdate(params)
        .then(res => {
          const isSucc = (res.status == 0);
          
          platform.notification({
            type: isSucc ? 'success' : 'error',
            title: isSucc ? this.$t('product.productTemplate.tips.tip8') : this.$t('product.productTemplate.tips.tip9'),
            message: !isSucc && res.message
          })

          if(isSucc) {
            this.reloadTab()
            this.goBack()
          }

        })
        .catch(err => {
          console.error('err', err)
        })
        .finally(() => {
          this.toggleLoading(false)
        })
    },
    // 返回
    goBack() {
      if(this.action == 'create') {
        let id = window.frameElement.dataset.id;
        return this.$platform.closeTab(id);
      }
      parent.frameHistoryBack(window);
    },
    // 获取提示信息
    genPlaceholder(field){
      return FormUtil.genPlaceholder(field);
    },
    // 将form对象转换为产品对象 提交表单使用
    packForm(fields, form) {
      let product = {
        id: form.id,
        attribute: {}
      }

      FormUtil.expandField(fields).forEach(field => {
        let {fieldName, isSystem} = field;
        let value = form[fieldName];
        let tv = null;

        if ((field.formType === 'location') && !value.isHaveLocation) {
          value = {};
        }
        if (field.formType === 'address' && !field.isSystem) {
          let all = formatAddress(value,'');

          value = {
            ...value,
          };

          all ? value.all = all : '';
        }
        if(field.fieldName === 'catalogId' && Array.isArray(value) && !value.length){
          value = null;
        }

        // 不为系统字段,放在attribute里面
        isSystem == 0
          ? product.attribute[fieldName] = value
          : product[fieldName] = value;
      })

      return product
    },
    reloadTab() {
      let fromId = window.frameElement.getAttribute('fromid');

      this.$platform.refreshTab(fromId);
    },
    closeAndOpenTab(id) {
      let fromId = window.frameElement.getAttribute('id');
      openAccurateTab({
        type:PageRoutesTypeEnum.PageProductTemplate,
        key:id,
        closeNowPage:true,
        fromId
      })
    },
    // 提交
    submit() {
      this.$refs.productTemplateEditForm.validate(false)
        .then(valid => {
          if (!valid) return Promise.reject('productTemplateEditForm validate fail.');

          this.toggleLoading()

          const submitForm = disposeFormSubmitTime(this.fields, this.form)

          let params = this.packForm(this.fields, submitForm);
          params = this.globalFormSubmissionDataProcessingHandler(this.fields, params)

          if (this.action == 'create' && this.hasRepeatRepair) {
            params.attribute.isRepeatRepair = this.$t('common.base.no')
          }
          if (this.action === 'edit') {
            return this.editProductTemplate(params);
          }

          this.createProductTemplate(params);
        })
        .catch(err => {
          console.error(err);
          this.toggleLoading(false)
        })
    },
    // 更新数据
    update({ field, newValue }){
      let {fieldName, displayName} = field;

      if (this.$appConfig.debug) {
        console.info(`[FormBuilder] ${displayName}(${fieldName}) : ${JSON.stringify(newValue)}`);
      }

      this.$set(this.form, fieldName, newValue);
    },
    toggleLoading(loading = true) {
      this.pending = loading
      this.loadingPage = loading
    }
  }
}
</script>

<style lang="scss">
body {
  padding: 10px;
}

.product-template-edit-container {
  background-color: #fff;
  height: 100%;
  width: 100%;
  overflow: auto;
  border-radius: 4px;

  .page-title {
    border-bottom: 1px solid #f4f7f5;
    padding: 12px 10px;

    display: flex;
    justify-content: space-between;

    // .iconfont {
    //   font-size: 12px;
    // }

    .title {
      display: flex;
      justify-content: space-between;
      span.text {
        line-height: 34px;
        margin-right: 12px;
      }
    }
  }
}

.form-builder{
  width: 700px;
  padding: 10px 0 0 10px;
  margin: 22px auto 0;

  .input-and-btn{
    display: flex !important;
    flex-flow: row nowrap;

    .form-item, .form-text, .form-select, .biz-team-select {
      flex: 1;
    }

    .base-dist-picker{
      padding-right: 0;
    }

    button{
      margin-left: 10px;
    }
  }
}
</style>